package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.SalesOrderInfoVo;
import com.ruoyi.system.domain.vo.SalesOrderRefundVo;
import com.ruoyi.system.mapper.RefundOrderInfoMapper;
import com.ruoyi.system.mapper.RefundOrderMapper;
import com.ruoyi.system.mapper.UnitMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Optional;

import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.SalesOrderMapper;
import com.ruoyi.system.service.ISalesOrderService;
import org.springframework.util.CollectionUtils;

/**
 * 销售单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-17
 */
@Service
public class SalesOrderServiceImpl implements ISalesOrderService 
{
    @Autowired
    private SalesOrderMapper salesOrderMapper;

    /**
     * 查询销售单
     * 
     * @param id 销售单主键
     * @return 销售单
     */
    @Override
    public SalesOrder selectSalesOrderById(Long id)
    {
        return salesOrderMapper.selectSalesOrderById(id);
    }

    /**
     * 查询销售单列表
     * 
     * @param salesOrder 销售单
     * @return 销售单
     */
    @Override
    public List<SalesOrder> selectSalesOrderList(SalesOrder salesOrder)
    {
        return salesOrderMapper.selectSalesOrderList(salesOrder);
    }

    /**
     * 新增销售单
     * 
     * @param salesOrder 销售单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSalesOrder(SalesOrder salesOrder)
    {
        salesOrder.setStatus("1");
        String userName = SecurityContextHolder.getUserName();
        salesOrder.setCreateOrderUser(userName);
        salesOrder.setCreateTime(DateUtils.getNowDate());

        List<SalesOrderInfo> salesOrderInfoList = salesOrder.getSalesOrderInfoList();
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (SalesOrderInfo salesOrderInfo : salesOrderInfoList) {
            totalAmount = totalAmount.add(salesOrderInfo.getTotalPrice());
        }

        salesOrder.setTotalAmount(totalAmount);
        int rows = salesOrderMapper.insertSalesOrder(salesOrder);
        insertSalesOrderInfo(salesOrder);
        return rows;
    }

    /**
     * 修改销售单
     * 
     * @param salesOrder 销售单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSalesOrder(SalesOrder salesOrder)
    {
        salesOrderMapper.deleteSalesOrderInfoBySalesOrderId(salesOrder.getId());
        insertSalesOrderInfo(salesOrder);
        return salesOrderMapper.updateSalesOrder(salesOrder);
    }

    /**
     * 批量删除销售单
     * 
     * @param ids 需要删除的销售单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSalesOrderByIds(Long[] ids)
    {
        salesOrderMapper.deleteSalesOrderInfoBySalesOrderIds(ids);
        return salesOrderMapper.deleteSalesOrderByIds(ids);
    }

    /**
     * 删除销售单信息
     * 
     * @param id 销售单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSalesOrderById(Long id)
    {
        salesOrderMapper.deleteSalesOrderInfoBySalesOrderId(id);
        return salesOrderMapper.deleteSalesOrderById(id);
    }

    @Autowired
    private RefundOrderMapper refundOrderMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Override
    public String salesOrderRefund(SalesOrderRefundVo salesOrderRefundVo) {
        String message = "退货成功";
        //退货业务处理
//         * 1、向退货单表
        RefundOrder refundOrder = new RefundOrder();
        refundOrder.setNo(IdUtils.simpleUUID());
        refundOrder.setSalesOrderId(salesOrderRefundVo.getId());
        refundOrder.setCreateTime(new Date());
        String userName = SecurityContextHolder.getUserName();
        refundOrder.setCreateOrderUser(userName);
        refundOrderMapper.insertRefundOrder(refundOrder);

//         * 2、退货单明细表插入数据（N）
        List<SalesOrderInfoVo> salesOrderInfoRefundList = salesOrderRefundVo.getSalesOrderInfoRefundList();
        List<RefundOrderInfo> refundOrderInfoList = new ArrayList<>();
        List<Unit> unitList = unitMapper.findAll();
//        退货的总数量
        Long returnQuantity = 0L;
        for (SalesOrderInfoVo salesOrderInfoVo : salesOrderInfoRefundList) {
            returnQuantity = returnQuantity + salesOrderInfoVo.getNumRefund();

            RefundOrderInfo refundOrderInfo = new RefundOrderInfo();
            refundOrderInfo.setReturnOrderId(refundOrder.getId());
            refundOrderInfo.setProductName(salesOrderInfoVo.getProductName());
            refundOrderInfo.setProductCode(salesOrderInfoVo.getProductCode());
            refundOrderInfo.setProductSpec(salesOrderInfoVo.getProductSpec());
            String unit = salesOrderInfoVo.getUnit();
            refundOrderInfo.setUnid(findIdByName(unitList, unit));
            refundOrderInfo.setNum(salesOrderInfoVo.getNum());
            refundOrderInfo.setPrice(salesOrderInfoVo.getPrice());
            refundOrderInfo.setNumRefund(salesOrderInfoVo.getNumRefund());
            refundOrderInfo.setTotalPrice(salesOrderInfoVo.getTotalPrice());
            refundOrderInfoList.add(refundOrderInfo);

        }
        if(!CollectionUtils.isEmpty(refundOrderInfoList)) {
            refundOrderMapper.batchRefundOrderInfo(refundOrderInfoList);
        }
        //3、根据id 更新销售单退货状态、退货的总数量
        SalesOrder salesOrder = new SalesOrder();
        salesOrder.setId(salesOrderRefundVo.getId());
        salesOrder.setHasReturn(1);

        salesOrder.setReturnQuantity(returnQuantity);
        salesOrderMapper.updateSalesOrder(salesOrder);


        return message;
    }

    public Long findIdByName(List<Unit> unitList, String name) {
        return unitList.stream()
                .filter(unit -> name.equals(unit.getName()))
                .map(Unit::getId)
                .findFirst().get();
    }

    /**
     * 新增销售单明细信息
     * 
     * @param salesOrder 销售单对象
     */
    public void insertSalesOrderInfo(SalesOrder salesOrder)
    {
        List<SalesOrderInfo> salesOrderInfoList = salesOrder.getSalesOrderInfoList();
        Long id = salesOrder.getId();
        if (StringUtils.isNotNull(salesOrderInfoList))
        {
            List<SalesOrderInfo> list = new ArrayList<SalesOrderInfo>();
            for (SalesOrderInfo salesOrderInfo : salesOrderInfoList)
            {
                salesOrderInfo.setSalesOrderId(id);
                list.add(salesOrderInfo);
            }
            if (list.size() > 0)
            {
                salesOrderMapper.batchSalesOrderInfo(list);
            }
        }
    }
}
